package net.maku.member.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.mybatis.service.impl.BaseServiceImpl;
import net.maku.member.convert.MemberDeptConvert;
import net.maku.member.entity.MemberDeptEntity;
import net.maku.member.query.MemberDeptQuery;
import net.maku.member.vo.MemberDeptVO;
import net.maku.member.dao.MemberDeptDao;
import net.maku.member.service.MemberDeptService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 部门管理
 *
 * @author 阿沐 babamu@126.com
 * @since 1.0.0 2025-03-15
 */
@Service
@AllArgsConstructor
public class MemberDeptServiceImpl extends BaseServiceImpl<MemberDeptDao, MemberDeptEntity> implements MemberDeptService {

    @Override
    public PageResult<MemberDeptVO> page(MemberDeptQuery query) {
        IPage<MemberDeptEntity> page = baseMapper.selectPage(getPage(query), getWrapper(query));
        return new PageResult<>(MemberDeptConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }

    @Override
    public List<MemberDeptVO> list(Long orgId) {
        return BeanUtil.copyToList(baseMapper.selectList(new LambdaQueryWrapper<MemberDeptEntity>().eq(MemberDeptEntity::getOrgId, orgId).eq(MemberDeptEntity::getStatus, 1)), MemberDeptVO.class);
    }

    private LambdaQueryWrapper<MemberDeptEntity> getWrapper(MemberDeptQuery query) {
        return new LambdaQueryWrapper<MemberDeptEntity>().like(StringUtils.isNotEmpty(query.getDeptName()), MemberDeptEntity::getDeptName, query.getDeptName())
                .like(StringUtils.isNotEmpty(query.getDeptCode()), MemberDeptEntity::getDeptCode, query.getDeptCode()).eq(MemberDeptEntity::getOrgId, query.getOrgId());
    }

    @Override
    public void save(MemberDeptVO vo) {
        MemberDeptEntity entity = MemberDeptConvert.INSTANCE.convert(vo);

        baseMapper.insert(entity);
    }

    @Override
    public void update(MemberDeptVO vo) {
        MemberDeptEntity entity = MemberDeptConvert.INSTANCE.convert(vo);

        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);
    }

}